package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;


    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //参数校验
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断是否存在作者信息
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不能为空");
        }
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());

        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注用户不存在");
        }

        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //关注
        if (dto.getOperation() == 0) {



            //4 创建数据（app用户关注和app用户粉丝）
            return followByUserId(user.getId(), apAuthor.getUserId(), dto.getArticleId());
        } else { // 取消关注
            return followCancelByUserId(user.getId(), apAuthor.getUserId());
        }
    }

    /**
     * 取消关注
     *
     * @param userId 当前用户
     * @param followUserId  被关注用户
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {

        // 删除当前用户关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUserId)
                .eq(ApUserFollow::getUserId, userId));

        // 删除被关注的粉丝信息
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getUserId, followUserId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 关注
     *
     * @param userId       当前普通用户id
     * @param followUserId 用户关注的作者对应的apuser id
     * @param articleId    文章id
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId) {
        //获取被关注作者对应的id
        ApUser followUser = apUserMapper.selectById(followUserId);

        if (followUser == null || followUser.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "关注用户不存在");
        }

        if (userId.intValue() == followUser.getId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不能关注自己");
        }

        //保存用户信息
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUser.getId())
                .eq(ApUserFollow::getId, userId)
        );
        if (apUserFollow != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short) 1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(followUser.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);


        //保存粉丝信息
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId, userId)
                .eq(ApUserFan::getId, followUser.getId())
        );

        if (apUserFan != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }

        apUserFan = new ApUserFan();
        apUserFan.setUserId(followUserId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());

        // 粉丝名称
        ApUser apUser = apUserMapper.selectById(userId);
        apUserFan.setFansName(apUser.getName());

        apUserFanMapper.insert(apUserFan);

        //发送消息
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setFollowId(followUserId);
        followBehaviorDto.setArticleId(articleId);
        followBehaviorDto.setUserId(apUser.getId());

        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
